<?php defined('SYSPATH') or die('No direct access allowed.');

class Controller_Catalogue extends Controller_ClientTemplate
{
    public function before()
    {
        parent::before();
        $this->template->styles = array('css/jquery.mCustomScrollbar.css' => 'screen',
                                        'css/prettyPhoto.css' => 'screen');
        
        $this->template->scripts = array('js/jquery-ui-1.8.16.custom.min.js',
                                         'js/jquery.easing.1.3.js',
                                         'js/jquery.mousewheel.min.js',
                                         'js/jquery.mCustomScrollbar.js',
                                         'js/jquery.json-2.3.min.js',
                                         'js/jquery.prettyPhoto.js');
    }

    public function action_index()
    {
        $path = Request::$current->param('path');

        $path_parts = is_null($path) ? array() : array_reverse(explode('/', $path));
        

        if(count($path_parts) == 0){
            $catalogue = DB::query(Database::SELECT, "SELECT *  
                                                      FROM catalogues 
                                                      WHERE parent_id=0
                                                      LIMIT 1")
                              ->as_object()
                              ->execute()
                              ->current();
            $this->show_catalogue($catalogue);            
        } else if(count($path_parts) == 1){
            $catalogue = DB::query(Database::SELECT, "SELECT *  
                                                      FROM catalogues 
                                                      WHERE href=:catalogue_href
                                                      LIMIT 1")
                              ->param(':catalogue_href', '/'.$path_parts[0])
                              ->as_object()
                              ->execute()
                              ->current();            
            $this->show_catalogue($catalogue);            
        } else if(count($path_parts) > 1) {
            $catalogue = DB::query(Database::SELECT, "SELECT c.* 
                                                      FROM `catalogues` as c
                                                      INNER JOIN `catalogues` as cc ON c.parent_id=cc.id
                                                      WHERE c.href=:catalogue_href AND cc.href=:ccatalogue_href
                                                      LIMIT 1")
                         ->param(':catalogue_href', '/'.$path_parts[0])
                         ->param(':ccatalogue_href', '/'.$path_parts[1])
                         ->as_object()
                         ->execute()
                         ->current();
            
            if(is_object($catalogue)){
                 $this->show_catalogue($catalogue);  
            } else {
                $images_path = Kohana::$config->load('products')->get('image_path');
                
                $product = DB::query(Database::SELECT, "SELECT p.*, CONCAT('$images_path', REPLACE(pi.file,'.','_min.')) as src
                                                        FROM `products` as p
                                                        INNER JOIN `catalogues` as c ON c.id=p.catalogue_id
                                                        LEFT JOIN `product_images` as pi ON pi.product_id=p.id
                                                        WHERE p.href=:product_href AND c.href=:catalogue_href")
                             ->param(':product_href', '/'.$path_parts[0])
                             ->param(':catalogue_href', '/'.$path_parts[1])
                             ->as_object()
                             ->execute();
                $rproduct = $product->current();
                
                $rproduct->src = array();
                foreach($product as $item){
                    array_push($rproduct->src, $item->src);
                }

                $this->show_product($rproduct);                    
            }
        }
    }
    
    public function action_filter()
    {        
        $this->auto_render = false;
        
        $products = array();
        if(Request::$initial->is_ajax()){            
            $catalogue_id = Arr::get($_REQUEST, 'catalogue_id', 0);
            $products = $this->filter($catalogue_id);                     
        }
        
        $this->response->body(View::factory('catalogue/product_items')
                                       ->set('products', $products));   
    }
    
    public function filter($catalogue_id, $href = '')
    {
        $products = array();
        
        if($href == '') $href = $this->catalogue_href($catalogue_id);
        
        $subcatalogs = DB::query(Database::SELECT, "SELECT c.id as id, c.href as href, COUNT(sc.id) as subs  
                                                    FROM `catalogues` as c
                                                    LEFT JOIN `catalogues` as sc
                                                    ON  c.id = sc.parent_id
                                                    WHERE c.parent_id=:catalogue_id
                                                    GROUP BY c.id")
                             ->param(':catalogue_id', $catalogue_id)
                             ->execute();
        if($subcatalogs->count()){
            foreach($subcatalogs as $subcatalog){
                if($subcatalog['subs'] == 0){
                    $products = array_merge($products, $this->products($subcatalog['id'], $href.$subcatalog['href']));
                } else {
                    $products = array_merge($products, $this->filter($subcatalog['id'], $href.$subcatalog['href']));
                }
            }
        } else
            $products = $this->products($catalogue_id, $href);
        
        return $products;
    }
    
    public function products($catalogue_id, $href)
    {
        $images_path = Kohana::$config->load('products')->get('image_path');
        
        $products = DB::select('products.id','products.price', 'products.name', array("CONCAT('$href', \"products.href\")", 'href'), array("CONCAT('$images_path', REPLACE(\"product_images.file\", '.', '_min.'))", 'src'))
                        ->from('products')
                        ->join('product_images', 'LEFT')
                        ->on('product_images.product_id', '=', 'products.id')
                        ->where('catalogue_id', '=', $catalogue_id)
                        ->group_by('products.id');
        
        $sex = Arr::get($_REQUEST, 'sex', 0);
        if($sex) $products = $products->where('sex', '=', $sex);
        
        $price = Arr::get($_REQUEST, 'price', 0);
        if($price){
            $price = explode('-', $price);
            $products = $products->where('price', '>=', intval($price[0]));
            $products = $products->where('price', '<=', intval($price[1]));
        }
        
        return $products->as_object()->execute()->as_array();

    }
    
    public function catalogue_href($catalogue_id)
    {
        $catalogue = DB::query(Database::SELECT, "SELECT c.href as href, pc.id as parent_id
                                               FROM catalogues as c
                                               LEFT JOIN catalogues as pc
                                               ON pc.id=c.parent_id
                                               WHERE c.id=:catalogue_id
                                               LIMIT 1")
                     ->param(':catalogue_id', $catalogue_id)
                     ->as_object()
                     ->execute()
                     ->current();
        
        return ($catalogue->parent_id) ? $this->catalogue_href($catalogue->parent_id).$catalogue->href : $catalogue->href;        
        
    }
    
    public function show_catalogue($catalogue)
    {
        if(is_object($catalogue)){
            
            $this->template->title = $catalogue->html_title;
            $this->template->keywords = $catalogue->html_keyword;
            $this->template->description = $catalogue->html_description;
            
            $products = Arr::get($_REQUEST, 'products', 0);

            if(!$products){
                $this->template->content = View::factory('catalogue/catalogue')
                                                ->set('title', $catalogue->name)
                                                ->set('content', $catalogue->content);
            } else {
                $sex = DB::query(Database::SELECT, "SELECT DISTINCT(sex) as sex FROM products")
                          ->execute()
                          ->as_array(NULL,'sex');

                $this->template->content = View::factory('catalogue/products')
                                                ->set('title', $catalogue->name)
                                                ->set('products', $this->filter($catalogue->id))
                                                ->set('catalogues', $this->get_catalogues(2))
                                                ->set('sex', $sex);
            }
            
            
            
        } else {
            $this->auto_render = false;            
            $this->response->status(404);
            $this->response->body(Request::factory('error/404')->execute());    
        }
    }
    
    public function show_product($product)
    {
        if(is_object($product)){
            $this->template->title = $product->name;
            $this->template->keywords = $product->html_keyword;
            $this->template->description = $product->html_description;
            $this->template->content = View::factory('catalogue/product')
                                            ->set('product', $product);
        } else {
            $this->auto_render = false;            
            $this->response->status(404);
            $this->response->body(Request::factory('error/404')->execute());            
        }
    }
    
    public function action_menu_plain()
    {
        $this->auto_render = false;
        
        $max_level = Request::$current->param('level', '2');
        $menu = View::factory('catalogue/menu_plain')->set('catalogues', $this->get_catalogues($max_level));
        
        Request::$current->response()->body($menu->render());     
    }
    
    public function action_menu()
    {
        $this->auto_render = false;
        
        $max_level = Request::$current->param('level', '-1');
        $menu = View::factory('catalogue/menu')->set('catalogues', $this->get_catalogues($max_level));
        
        Request::$current->response()->body($menu->render()); 
    }
    
    public function get_catalogues($max_level = -1, $parent_id = 0, $cur_level = 1)
    {
        $catalogues = array();

        $result = DB::query(Database::SELECT, "SELECT c1.id as `id`, c1.name as `name`, c1.href as `href`, 
                                                          c1.parent_id as `parent_id`, 
                                                          (COUNT(c2.name)>0) as `subcatalogues` 
                                                 FROM  `catalogues` AS  `c1` 
                                                 LEFT JOIN  `catalogues` AS  `c2` ON c2.parent_id = c1.id
                                                 WHERE (c1.parent_id =:parent_id AND c1.hide='show') 
                                                 GROUP BY c1.href
                                                 ORDER BY c1.pos")
                    ->param(':parent_id', $parent_id)
                    ->execute()
                    ->as_array(); 
        
        foreach ($result as $catalogue) {
            if($catalogue['subcatalogues'] && ($cur_level < $max_level || $max_level == -1))
                $catalogue['subcatalogues'] = $this->get_catalogues($max_level, $catalogue['id'], $cur_level + 1);
            else
                unset($catalogue['subcatalogues']);
            $catalogues[] = $catalogue;
        }
        return $catalogues;
    }    
    
}